#include "logMessage.hpp"

#pragma once
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

enum
{
    SOCKET_ERR = 1,
    USAGE_ERR,
    CONNECT_ERR,
};

class TcpClient
{
public:
    TcpClient(const string &serverip, const uint16_t &serverport)
        : _sock(-1), _serverIP(serverip), _serverPort(serverport)
    {
    }
    ~TcpClient()
    {
        close(_sock);
    }

    void InitClient()
    {
        // 1.创建套接字
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(FATAL, "Create Socket FAIL!");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "Create Socket Success!");

        // 2. 不需要显示的bind，OS会自动bind，在发起链接的时候
        // 3. No need listen    4. No need accept
    }

    void Start()
    {
        // 5. 要发起链接 connect
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverPort);
        server.sin_addr.s_addr = inet_addr(_serverIP.c_str());

        if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
        {
            // 发起连接fail
            logMessage(FATAL, "Connect Socket Fail!");
            exit(CONNECT_ERR);
        }

        string buffer;
        char message[1024];
        for (;;)
        {
            // 进行IO操作
            cout << "Please Enter# ";
            getline(cin, buffer);
            // fgets(buffer, sizeof(buffer) - 1, stdin);
            // getchar();
            write(_sock, buffer.c_str(), sizeof(buffer));

            // 读取数据
            int n = read(_sock, message, sizeof(message) - 1);
            if (n > 0)
            {
                message[n] = 0;
                cout << "Server 回复# " << message << endl;
            }
            else
            {
                break; // 结束
            }
        }
    }

private:
    int _sock;
    string _serverIP;
    uint16_t _serverPort;
};